package com.hoperun.product.activity;

import android.app.DatePickerDialog;
import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hoperun.product.Models.HuanBiModel;
import com.hoperun.product.base.MIP_BaseActivity;
import com.hoperun.product.net.IServiceImpl;
import com.hoperun.product.net.RequestServiceImpl;
import com.hoperun.product.util.ParseUtils;
import com.hoperun.product.util.SharedPreUtil;
import com.hoperun.product.view.SimpleDialog;
import com.hoperun.yieldmgr.R;

import org.json.JSONArray;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ManyConfirmActivity extends MIP_BaseActivity {

    @BindView(R.id.usertextview)
    TextView usertextview;
    @BindView(R.id.input_dateTv)
    TextView inputDateTv;
    @BindView(R.id.input_dateLl)
    LinearLayout inputDateLl;
    @BindView(R.id.input_dateTv2)
    TextView inputDateTv2;
    @BindView(R.id.input_dateL2)
    LinearLayout inputDateL2;
    @BindView(R.id.editpihao)
    EditText editpihao;
    @BindView(R.id.editchandi)
    EditText editchandi;
    @BindView(R.id.editshazhi)
    EditText editshazhi;
    @BindView(R.id.spinnerbeizhu)
    Spinner spinnerbeizhu;
    @BindView(R.id.recylistview)
    RecyclerView recylistview;
    @BindView(R.id.input_nodateImg)
    ImageView inputNodateImg;

    //工种
    ArrayAdapter beizhuSpinnerAdapter;
    ArrayList<String> beizhustrlist = new ArrayList<String>();

    QuickAdapter quickAdapter;
    ArrayList<HuanBiModel> daolist = new ArrayList<HuanBiModel>();
    ArrayList<HuanBiModel> savedaolist = new ArrayList<HuanBiModel>();
    @BindView(R.id.query_queryBtn)
    Button queryQueryBtn;
    @BindView(R.id.query_saveBtn)
    Button querySaveBtn;
    @BindView(R.id.input_countTv)
    TextView inputCountTv;
    //日期
    String mJobDate;
    String mJobDate2;
    int dataType=1;
    private SimpleDateFormat dateFormat_ZH = new SimpleDateFormat("yyyy年MM月dd日");
    private SimpleDateFormat dateFormat_EN = new SimpleDateFormat("yyyy-MM-dd");
    JSONObject user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_many_confirm);
        ButterKnife.bind(this);
        String jsonuser = SharedPreUtil.getValue(this, SharedPreUtil.USERHUANGBEAN, "").toString();
        user = JSONObject.parseObject(jsonuser);
        //mJobDate=dateFormat_EN.format(new Date(System.currentTimeMillis()));
       // inputDateTv.setText(mJobDate);
        usertextview.setText("登录人:"+user.getString("XM"));

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recylistview.setLayoutManager(layoutManager);
        //给RecyclerView设置适配器
        quickAdapter = new QuickAdapter();
        recylistview.setAdapter(quickAdapter);
        //工种
        beizhuSpinnerAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, beizhustrlist);
        beizhuSpinnerAdapter.setDropDownViewResource(R.layout.spinner_drop_item);
        spinnerbeizhu.setAdapter(beizhuSpinnerAdapter);
        //默认查

        //工种
        getbeizhu();
        RequestServiceImpl.getserverTime(mMIPHandler, IServiceImpl.getservertime);
    }



    public class QuickAdapter extends BaseQuickAdapter<HuanBiModel, BaseViewHolder> {
        public QuickAdapter() {
            super(R.layout.huanpi_list_item, daolist);
        }


        @Override
        protected void convert(final BaseViewHolder holder, HuanBiModel item) {
            TextView item_shazhi = holder.getView(R.id.item_shazhi);
            TextView item_nianxiang = holder.getView(R.id.item_nianxiang);
            TextView item_chandi = holder.getView(R.id.item_chandi);
            TextView item_pihao = holder.getView(R.id.item_pihao);
            TextView item_pandian = holder.getView(R.id.item_pandian);
            TextView item_yuanliao = holder.getView(R.id.item_yuanliao);
            TextView item_beizhu = holder.getView(R.id.item_beizhu);
            TextView item_xinchandi = holder.getView(R.id.item_xinchandi);
            TextView item_xinpihao = holder.getView(R.id.item_xinpihao);
            CheckBox input_item_checkBox = holder.getView(R.id.input_item_checkBox);

            input_item_checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    daolist.get(holder.getLayoutPosition()).setBoxcheck(isChecked);
//                    mCount = 0;
//                    for (int i = 0; i < daolist.size(); i++) {
//                        if (daolist.get(i).isBoxcheck() == true) {
//                            mCount++;
//                        }
//                    }
                }
            });

            item_shazhi.setText(item.getSZQC() == null ? "" : item.getSZQC());
            item_nianxiang.setText(item.getDIRECTION() == null ? "" : item.getDIRECTION());
            item_chandi.setText(item.getORIPLACE() == null ? "" : item.getORIPLACE());
            item_pihao.setText(item.getBATCHNO() == null ? "" : item.getBATCHNO());
            item_pandian.setText(item.getZBPD() == null ? "" : item.getZBPD());
            item_yuanliao.setText(item.getJGYQ() == null ? "" : item.getJGYQ());
            item_beizhu.setText(item.getREMARK() == null ? "" : item.getREMARK());
            item_xinchandi.setText(item.getN_ORIPLACE() == null ? "" : item.getN_ORIPLACE());
            item_xinpihao.setText(item.getN_BATCHNO() == null ? "" : item.getN_BATCHNO());
            input_item_checkBox.setChecked(item.isBoxcheck());

        }
    }

    public void getbeizhu() {//获取备注
        showWait();
        RequestServiceImpl.querybeizhu(mMIPHandler, IServiceImpl.querybeizhu);
    }

    public void querylist(String JobDate, String JobDate2,String cd, String ph, String shazhi, String remark) {//根据条件查询
        showWait();
        RequestServiceImpl.queryhuanpilist(mMIPHandler, IServiceImpl.query_hanpi_list,user.getString("XTYHID"), JobDate,JobDate2, cd, ph, shazhi, remark);
    }


    @Override
    public void onPostHandle(int requestType, Object objBody, boolean error) throws Exception {
        String msg = "";
        String opt = "";
        if (error) {
            // if (requestType != IServiceImpl.getYuanliaoInfo) {
            stopWait();
            // }
            switch (requestType) {
                case IServiceImpl.query_hanpi_list://根据条件查询
                    try {
                        org.json.JSONObject jsonObj = new org.json.JSONObject((String) objBody);
                        if (jsonObj.getInt("Code") == 0) {
                            if (jsonObj.getJSONArray("Result") != null && jsonObj.getJSONArray("Result").length() > 0) {
                                JSONArray jsonArray = jsonObj.getJSONArray("Result");
                                daolist.clear();
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    HuanBiModel daoshaModel = ParseUtils.parse(jsonArray.getJSONObject(i).toString(), HuanBiModel.class);
                                    daoshaModel.setBoxcheck(false);
                                    daolist.add(daoshaModel);
                                }
                            } else {
                                daolist.clear();
                            }
                            quickAdapter.notifyDataSetChanged();
                            checkListview();

                        } else {
                            SimpleDialog.show(this, jsonObj.getString("Message"));
                        }
                    } catch (Exception e) {

                    }
                    break;
                case IServiceImpl.querybeizhu://备注
                    try {
                        org.json.JSONObject jsonObj = new org.json.JSONObject((String) objBody);
                        if (jsonObj.getInt("Code") == 0) {
                            JSONArray jsonArray = jsonObj.getJSONArray("Result");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                beizhustrlist.add(jsonArray.getJSONObject(i).getString("sjxz"));
                            }
                            beizhustrlist.add(0, "请选择");
                            quickAdapter.notifyDataSetChanged();
                            beizhuSpinnerAdapter.notifyDataSetChanged();
                        }
                    } catch (Exception e) {

                    }
                    break;

                case IServiceImpl.updatehuanpi://更新
                    try {
                        org.json.JSONObject jsonObj = new org.json.JSONObject((String) objBody);
                        if (jsonObj.getInt("Code") == 0) {
                            SimpleDialog.show(this, "确认成功!");
//                            for (int i = 0; i < daolist.size(); i++) {
//                                daolist.get(i).setBoxcheck(false);
//                            }
                            //刷新请求
                            String remark = spinnerbeizhu.getSelectedItem().toString();
                            if (remark.equals("请选择")) {
                                remark = "";
                            }
                            querylist(mJobDate,mJobDate2 ,editchandi.getEditableText().toString().trim(), editpihao.getEditableText().toString().trim(), editshazhi.getEditableText().toString().trim(), remark);

                        } else {
                            SimpleDialog.show(this, jsonObj.getString("Message"));
                        }
                    } catch (Exception e) {

                    }
                    break;

                case IServiceImpl.getservertime://获取时间
                    try {
                        org.json.JSONObject jsonObj = new org.json.JSONObject((String) objBody);
                        if (jsonObj.getInt("Code") == 0) {
                            String time=jsonObj.getString("Result");
                            mJobDate=dateFormat_EN.format(dateFormat_EN.parse(time));
                            inputDateTv.setText(dateFormat_ZH.format(dateFormat_EN.parse(time)));

                            mJobDate2=dateFormat_EN.format(dateFormat_EN.parse(time));
                            inputDateTv2.setText(dateFormat_ZH.format(dateFormat_EN.parse(time)));

                            querylist(mJobDate,mJobDate2, "", "", "", "");
                        }

                    }catch (Exception e){
                    }
                    break;


            }

        } else {
            stopWait();
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show();

        }
    }

    /**
     * 检查listview是否为空
     */
    private void checkListview() {
        if (daolist.size() > 0) {
            recylistview.setVisibility(View.VISIBLE);
        } else {
            recylistview.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.query_queryBtn, R.id.query_saveBtn, R.id.input_dateLl,R.id.input_dateL2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.input_dateLl:
                dataType=1;
                setDate();
                break;
            case R.id.input_dateL2:
                dataType=2;
                setDate();
                break;
            case R.id.query_queryBtn:
                String remark = spinnerbeizhu.getSelectedItem().toString();
                if (remark.equals("请选择")) {
                    remark = "";
                }
                querylist(mJobDate,mJobDate2, editchandi.getEditableText().toString().trim(), editpihao.getEditableText().toString().trim(), editshazhi.getEditableText().toString().trim(), remark);

                break;
            case R.id.query_saveBtn:
                savedaolist.clear();
                for (int i = 0; i < daolist.size(); i++) {
                    if (daolist.get(i).isBoxcheck()) {
                        // 添加到需要保存的列表中
                        savedaolist.add(daolist.get(i));
                    }
                }
                if (daolist.size() == 0) {
                    SimpleDialog.show(this, "当前列表为空，请添加数据！");
                    return;
                }

                if (savedaolist.size() == 0) {
                    SimpleDialog.show(this, "请勾选需要确认的数据！");
                    return;
                }

                showWait();
                RequestServiceImpl.updatehuanpi(mMIPHandler, IServiceImpl.updatehuanpi, user.getString("XTYHID"), user.getString("XM"),savedaolist);
                break;
        }
    }

    /**
     * 设置日期
     */
    private void setDate() {
        String[] strNow =dataType==1? mJobDate.toString().split("-"): mJobDate2.toString().split("-");
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, mOnDateSetListenernew, Integer.parseInt(strNow[0]), Integer.parseInt(strNow[1])-1, Integer.parseInt(strNow[2]));
        datePickerDialog.show();
    }

    /**
     * 日期选择监听器
     */
    DatePickerDialog.OnDateSetListener mOnDateSetListenernew = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            String date = year + "年" + String.format("%02d", month + 1) + "月" + String.format("%02d", dayOfMonth) + "日";
            if(dataType==1){
                inputDateTv.setText(date);
                mJobDate = year + "-" + String.format("%02d", month + 1) + "-" + String.format("%02d", dayOfMonth);
            }else{
                inputDateTv2.setText(date);
                mJobDate2 = year + "-" + String.format("%02d", month + 1) + "-" + String.format("%02d", dayOfMonth);
            }


        }
    };


//    private Calendar getDefaultDate() {
//        Calendar calendar = Calendar.getInstance();
//        // 获取当前年月日
//        int year = calendar.get(Calendar.YEAR);
//        int month = calendar.get(Calendar.MONTH) + 1;
//        int day = calendar.get(Calendar.DAY_OF_MONTH);
//        int hour = calendar.get(Calendar.HOUR_OF_DAY);
//        int minute = calendar.get(Calendar.MINUTE);
//        if (hour < 7 || (hour == 7 && minute < 30)) {
//            day -= 1;
//        }
//        calendar.set(year, month, day);
//        return calendar;
//    }

}